class UsersController < ApplicationController

  before_filter :require_user, :except => [:new, :create]
  before_filter :require_admin, :except => [:edit, :update, :new, :create, :show]

  def new
    @user = User.new
    @user.person = Person.new
    if request.xhr?
      render :layout => false
    end
  end

  def create
    @user = User.new
    @user.person = Person.new
    @user.attributes = params[:user]
    @user.person.visitor = Visitor.new
    @user.person.visitor.name = @user.person.name
    @user.person.visitor.email = @user.email
    @user.person.visitor.phone = @user.person.phone
    if @user.save
      flash[:notice] = "User #{@user.email} successfully created."
      if current_user.person.is_keyholder?
        redirect_to users_path
      else
        redirect_to dashboard_path
      end
    else
      render :action => "new"
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    @user.update_attributes(params[:user])
    if @user.save
      if current_user.person.is_keyholder? && !(current_user == @user)
        flash[:notice] = "User #{@user.person.name}(#{@user.email}) successfully updated."
        redirect_to users_path
      else
        flash[:notice] = "Profile successfully updated."
        redirect_to dashboard_path
      end
      
    end
  end

  def destroy
    @user = User.find(params[:id])
    @user.destroy
    flash[:notice] = "User #{@user.person.name}(#{@user.email}) removed."
    redirect_to(users_path)
  end

  def index
    @users = User.find(:all, :order => "created_at DESC")
    if request.xhr?
      render :layout => false
    end
  end

  def show
    @user = User.find(params[:id])
  end

end
